import { publicMsg } from "./publicMsg.js"
import { RouterTo } from "./util_base.js"
function is_JSON(str) {
	//判断一个字符串是否为json格式
	/*此函数对于一些特殊情况会有例外
	 * JSON.parse('123'); // 123
	 * JSON.parse('{}'); // {}
	 * JSON.parse('true'); // true
	 * JSON.parse('"foo"'); // "foo"
	 * JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
	 * JSON.parse('null'); // null
	 * */
    if (typeof str == 'string') {
        try {
            JSON.parse(str);
            return true;
        } catch(e) {
            return false;
        }
    }else{
    	return false;
    }
}
function inStorage(method,key,value) {
	if(method === 'set'){
		if(typeof value != 'string'){
			localStorage.setItem(key,JSON.stringify(value));
		}else{
			localStorage.setItem(key,value);
		}
		
	}else if (method === 'get'){
		//get时value 为 this
		var _this = value;
		var val = localStorage.getItem(key);
		if(env == "develop"){
			if(!val||val=="undefined"||val=="null"){
//				console.debug("我可能找不到这个参数了","键"+key+"值"+val);
				console.log("%c我可能找不到这个参数了键 "+key+"值"+val, "background-color:pink;color:#330696");
				if(!!_this){
					console.error("完蛋了，我不应出现在这里的")
				}else{
					
					return false;
				}
				return;
			}
		}else{
			if(!val||val=="undefined"||val=="null"){
				inStorage("clear");
				if(!!_this){
					RouterTo(_this, "/");
				}else{
					return false;
				}
				return;
			}
		}
		if(is_JSON(val)){
			return val = JSON.parse(val);
		}else{
			return val;
		}
	}else if (method === 'clear'){
		if(!!key){
//			var val = localStorage.getItem(key);
			localStorage.removeItem(key);
		}else{
			localStorage.clear();
		}
	}
}
function getQueryStringArgs(){
		var str = window.location.href.split("?")[1]
		console.log(str);
		if(str){
		var qs = (location.search.length>0 ? location.search.substring(1) : str.substring(0,str.length-2));
		}else{
			var qs = '';
		}
		console.log(qs);
		var args = {};
		var items = qs.length?qs.split("&"):[];
		var item = null;
		var name = null;
		var value = null;
		var len = items.length;
		for(var i = 0;i<len;i++){
			item = items[i].split("=");
			name = decodeURIComponent(item[0]);
		    value = decodeURIComponent(item[1]);
		    
		    if(name.length){
		    	args[name] = value;
		    }
		}
		return args;
}
function getLoacl(http){
	var _url = "";
	if(window.location.hostname == "localhost"){
		_url = http+"://192.168.0.82:7091";
		return _url;
	}
	if(!window.location.port){
		_url = http+"://"+window.location.hostname;
	}else{
		_url = http+"://" + window.location.hostname+":"+window.location.port;
	}
	return _url;
}
function changeColor(){
	 var ranColor = '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
	 return ranColor;
}
export { inStorage,is_JSON,getQueryStringArgs,changeColor,getLoacl }
